from django.conf import settings
from django.db import DatabaseError
from django.shortcuts import render
from django.views import View
from django.http import response
from django_redis import get_redis_connection

from utils.captcha.captcha import captcha
from utils.response_code import RETCODE


class ImageCodeView(View):
    """用户验证视图"""
    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一标识图形验证码所属于的用户
        :return: image/jpeg
        """
        # 生成图片验证码
        text, image = captcha.generate_captcha()
        # 保存图片验证码
        image_code_redis_cli = get_redis_connection('verify_image_code')
        image_code_redis_cli.setex(f"img_{uuid}", 300, text)
        # 返回验证码图片
        return response.HttpResponse(content=image, content_type='image/jpeg')


class SmscodeView(View):
    """短信验证码视图"""

    def get(self, request, mobile):
        """
        :param reqeust: 请求对象
        :param mobile: 手机号
        :return: JSON
        """
        # sms_codes/(?P<mobile>1[3-9]\d{9})/'/?image_code=' + this.image_code + '&image_code_id=' + this.image_code_id
        # 1.解析校验参数--mobile 不用校验
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        # 2.校验图形验证码 如果正确 发送验证码, 不正确 直接返回
        # 2.1 根据uuid 去redis数据库查询 图片验证码
        img_code_cli = get_redis_connection('verify_image_code')
        redis_img_code = img_code_cli.get(f"img_{uuid}")
        # 判断服务器返回的验证
        if redis_img_code is None:
            return response.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码已过期,请刷新后重试!'})
        # 如果有值 删除redis服务器上的图形验证码
        try:
            img_code_cli.delete(f"img_{uuid}")
        except DatabaseError as e:
            settings.LOGGER.error(e)

        # 2.2 和前端传过来的进行做对比
        # 千万注意: 在redis取出来的是 bytes 类型不能直接做对比 decode()
        if image_code.lower() != redis_img_code.decode().lower():
            return response.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '验证码输入有误,请重试!'})

        # 2.3 校验是否频繁请求发送短信
        sms_code_cli = get_redis_connection('sms_code')
        sms_send_flag = sms_code_cli.get(f"sms_flag_{mobile}")
        if sms_send_flag:
            return response.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '短信发送频繁,请稍后重试!'})
        # 3.生成短信验证码,redis-存储
        from random import randint
        sms_code = f"{randint(0, 999999):06d}"

        # 利用pipeline异步写入redis数据库,防止阻塞
        p1 = sms_code_cli.pipeline()
        p1.setex(f"sms_{mobile}", 300, sms_code)
        p1.setex(f"sms_flag_{mobile}", 60, 1)
        p1.execute()
        # 4.让第三方 容联云-给手机号-发送短信
        # from utils.yuntongxun.sms import CCP
        # CCP().send_template_sms(mobile,{sms_code, 5}, 1)
        # 使用celery异步发送短信,减少用户等待,防止阻塞
        from libs.celery_tasks.sendmsg.tasks import ccp_send_sms_code
        ccp_send_sms_code.delay(mobile, sms_code)
        # 5.告诉前端短信发送完毕
        return response.JsonResponse({'code': RETCODE.OK, 'errmsg': '短信发送成功'})
